package main

import (
	"context"
	"errors"
	"google.golang.org/grpc"
	"learn-go-project/grpc/demo01/message"
	"net"
	"time"
)

type OrderServiceImpl struct {
}

func (o *OrderServiceImpl) GetOrderInfo(ctx context.Context, request *message.OrderRequest) (*message.OrderInfo, error) {
	orderMap := map[string]message.OrderInfo{
		"202011060001": {OrderId: "202011060001", OrderName: "衣服", OrderStatus: "已付款"},
		"202011060002": {OrderId: "202011060002", OrderName: "零食", OrderStatus: "已付款"},
		"202011060003": {OrderId: "202011060003", OrderName: "食品", OrderStatus: "未付款"},
	}

	var response = &message.OrderInfo{}
	current := time.Now().Unix()

	if request.TimeStamp > current {
		*response = message.OrderInfo{OrderName: "", OrderId: "0", OrderStatus: "订单信息异常"}
	} else {
		result := orderMap[request.OrderId]
		if result.OrderId != "" {
			*response = result
		} else {
			return nil, errors.New("server error")
		}
	}
	return response, nil
}

func main() {
	server := grpc.NewServer()

	message.RegisterOrderServiceServer(server, new(OrderServiceImpl))

	lis, err := net.Listen("tcp", ":9000")

	if err != nil {
		panic(err)
	}
	server.Serve(lis)
}
